#Install packages
pacman::p_load(tidyverse,
               skimr,
               readxl)

library(readxl)
library(haven)
library(dplyr)
library("MASS")
library("scatterplot3d")
library("poLCA")

n2 <- read_dta("~/n2a.dta")
view(n2)
set.seed(43)
# Assuming your dataset is called df
df <- data.frame(intention1 = rnorm(10), con_indemnity_1 = rnorm(10), 
                 con_indemnity_2 = rnorm(10), con_indemnity_3 = rnorm(10),
                 risk_perception1_1 = rnorm(10), trust1_1 = rnorm(10), 
                 fam_identity_1 = rnorm(10), e_nr_2_1 = rnorm(10))

# Rename the columns
df <- df %>%
  rename("Intention to call a vet to examine their herd" = intention1,
         "Motivation to self-invest in biosecurity" = con_indemnity_1,
         "Likelihood of buying livestock insurance" = con_indemnity_2,
         "Readiness to report infections" = con_indemnity_3,
         "Risk perception" = risk_perception1_1,
         "Trust in government agencies" = trust1_1,
         "Farmer knowledge about biosecurity" = fam_identity_1,
         "Confidence in neighbour to biosecure" = e_nr_2_1)

# Check the renamed columns
names(df)
view(df)

# Specify the formula for the basic LCA model 
formula <- cbind(intention1, con_indemnity_1, con_indemnity_2, con_indemnity_3, risk_perception1_1, trust1_1, fam_identity_1, e_nr_2_1 ) ~ 1

# Fit the LCA model
reg <- poLCA(formula, data = n2, nclass = 3, maxiter = 1000, graphs = TRUE, tol = 1e-10, na.rm = TRUE, probs.start = NULL)

# Assuming reg3$probs.start is a list of vectors or matrices
probs.start <- reg$probs.start

# Loop over each element in probs.start
for (j in seq_along(probs.start)) {
  if (is.vector(probs.start[[j]])) {
    # Modify the j-th element if it's a vector
    if (length(probs.start[[j]]) >= 3) {
      probs.start[[j]] <- probs.start[[j]][c(3, 1)]
    } else {
      stop("Vector at index ", j, " does not have at least 3 elements.")
    }
  } else if (is.matrix(probs.start[[j]])) {
    # Modify the j-th element if it's a matrix
    if (ncol(probs.start[[j]]) >= 3) {
      probs.start[[j]] <- probs.start[[j]][, c(3, 1)]
    } else {
      stop("Matrix at index ", j, " does not have at least 3 columns.")
    }
  } else {
    stop("Element at index ", j, " is neither a vector nor a matrix.")
  }
}

# Use the modified probs.start in the poLCA function
reg <- poLCA(formula, n2, nclass = 3, probs.start = probs.start, graphs=TRUE)


#Different latent class models
lc2 <- poLCA(formula,n2,nclass=2)
lc3 <- poLCA(formula,n2,nclass=3)
lc4 <- poLCA(formula,n2,nclass=4,maxiter=5000)
lc5 <- poLCA(formula,n2,nclass=5,maxiter=5000)
# Summarize the results


